package cn.org.mrliu.code.generator.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
	static String driverClassName = "com.mysql.jdbc.Driver";
	static String url = "jdbc:mysql://localhost:3307/ssm?characterEncoding=UTF-8";
	static String username = "root";
	static String password = "root";

	static {
		try {
			Class.forName(driverClassName);
		} catch (ClassNotFoundException e) {
			throw new ExceptionInInitializerError("加载驱动错误!");
		}
	}

	public static Connection getConnection() throws Exception {
		try {
			return DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			throw new Exception("获取连接失败!");
		}
	}

	public static <T>T query(String sql,ResultSetHandler<T> resultSetHandler,Object... objects) {
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet rs = null;
		try {
			connection = DBUtil.getConnection();
			statement = connection.prepareStatement(sql.toString());
			if (objects != null && objects.length > 0) {
				for (int i = 0; i < objects.length; i++) {
					Object object = objects[i];
					statement.setObject((i+1), object);
				}
			}
			rs = statement.executeQuery();
			return resultSetHandler.handle(rs);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(rs, statement, connection);
		}
		return null;
	}

	public static void close(PreparedStatement statement, Connection connection) {
		close(null, statement, connection);
	}

	public static void close(ResultSet rs, PreparedStatement statement, Connection connection) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
